//
//  AppDelegateJPush.swift
//  MT
//
//  Created by ooops on 2019/12/16.
//  Copyright © 2019 张强. All rights reserved.
//

import Foundation
import UIKit


extension AppDelegate {
    func registerJPush(application: UIApplication, options: [UIApplication.LaunchOptionsKey : Any]?) {
        /// APNS
        let entity: JPUSHRegisterEntity = JPUSHRegisterEntity()
        entity.types = Int(JPAuthorizationOptions.alert.rawValue | JPAuthorizationOptions.badge.rawValue | JPAuthorizationOptions.sound.rawValue)
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        #if DEBUG
        JPUSHService.setup(withOption: options, appKey: JPushAppSecretKey, channel: "APP Store", apsForProduction: false)
        #else
        JPUSHService.setup(withOption: options, appKey: JPushAppSecretKey, channel: "APP Store", apsForProduction: true)
        #endif
        
        
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
    }
}

extension AppDelegate: JPUSHRegisterDelegate {
    func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable : Any]!) {
        
    }
    
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
//        let userInfo: [AnyHashable : Any] = notification.request.content.userInfo
//        if ((notification.request.trigger as? UNPushNotificationTrigger) != nil) {
//            JPUSHService.handleRemoteNotification(userInfo)
//            self.didRecevie(userInfo, needToConversation: false)
//        }
//
//        completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue))
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        let userInfo: [AnyHashable : Any] = response.notification.request.content.userInfo
        if ((response.notification.request.trigger as? UNPushNotificationTrigger) != nil) {
            JPUSHService.handleRemoteNotification(userInfo)
            self.didRecevie(userInfo, needToConversation: true)
        }
        
        completionHandler()
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification!) {
        
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        
        JPUSHService.handleRemoteNotification(userInfo)
        
        self.didRecevie(userInfo, needToConversation: true)
        
        completionHandler(UIBackgroundFetchResult.newData)
        
    }
    
    func didRecevie(_ notification: [AnyHashable : Any], needToConversation: Bool) {
        if needToConversation == false {
            return
        }
        if let customDictionary: [String : Any] = notification["custom"] as? [String : Any] {
            /// 个人聊天信息
            if let userName = customDictionary["userName"] as? String {
                if let conversation: JMSGConversation = JMSGConversation.singleConversation(withUsername: userName) {
                    let vc = JCChatViewController(conversation: conversation)
                    if let baseTabBarViewController = (self.window?.rootViewController as? BaseTabBarViewController) {
                        baseTabBarViewController.selectedIndex = 1
                        conversation.clearUnreadCount()
                        if let nav = baseTabBarViewController.selectedViewController as? BaseNavController {
                            DispatchQueue.main.after(0.25) {
                                nav.pushViewController(vc, animated: true)
                            }
                        }
                    }
                }
            } else {
                /// 俱乐部聊天信息
                if let gid = customDictionary["gid"] as? String {
                    if let conversation: JMSGConversation = JMSGConversation.groupConversation(withGroupId: gid) {
                        let vc = JCChatViewController(conversation: conversation)
                        if let baseTabBarViewController = (self.window?.rootViewController as? BaseTabBarViewController) {
                            baseTabBarViewController.selectedIndex = 1
                            conversation.clearUnreadCount()
                            if let nav = baseTabBarViewController.selectedViewController as? BaseNavController {
                                DispatchQueue.main.after(0.25) {
                                    nav.pushViewController(vc, animated: true)
                                }
                            }
                        }
                    }
                }
            }
        }
        
        /// 处理通知消息界面跳转问题
        /*
         /// app出于后台接收到的个人消息的通知
         {
             "custom": {
                 "userName": "mitu_5SEfpnBB"
             },
             "_j_uid": 34620930584,
             "_j_msgid": 5929159959,
             "_j_business": 32,
             "aps": {
                 "alert": {
                     "body": "almost: Gogikgkg "
                 },
                 "sound": "default",
                 "badge": 1
             },
             "_j_type": "jmessage"
         }
         
         /// app出于后台接收到的俱乐部消息的通知
         {
             "custom": {
                 "gid": "41983703"
             },
             "_j_business": 32,
             "aps": {
                 "alert": {
                     "body": "almost(苏苏大家): Ccncnw"
                 },
                 "sound": "default",
                 "badge": 1
             },
             "_j_msgid": 5929182119,
             "_j_uid": 34620930584,
             "_j_type": "jmessage"
         }
         */
    }
    
}
